class DPagination {
  constructor(dataName) {
    this.loading = false;
    this.finished = false;
    this.dataName = dataName;
    this.dataPath = `${dataName}`;
    this.pages = 0; //* 本地存储的实际页数
    this.length = 0; //* 本地存储的数据条数
    this.limit = 15; //* 每页显示的数量
    this.loadPage = 1; //* 每次加载累加的页数
  }
  bind(page) {
    this.PageThis = page;
    return this;
  }
  push(data) {
    const PageThis = this.PageThis["data"];
    let dataLength = Object.keys(PageThis[this.dataName]).length;
    let pageKey = "page_";
    if (dataLength > 0) {
      let lastPage = Object.values(PageThis[this.dataName]).pop();
      if (lastPage.length >= this.limit) {
        pageKey += dataLength + 1;
      } else {
        pageKey += dataLength;
      }
    } else {
      pageKey += "1";
    }
    let pagePath = `${this.dataPath}.${pageKey}`;

    const setData = {};
    if (PageThis[this.dataPath][pageKey]) {
      let lastIndex = PageThis[this.dataPath][pageKey].length;
      setData[`${pagePath}[${lastIndex}]`] = data;
    } else {
      setData[pagePath] = Array.isArray(data) ? [...data] : data;
    }

    this.PageThis.setData(setData, () => {
      this.length++;
      this.pages++;
      this.loadPage++;
    });
    return this;
  }
  removePage(pages) {
    this.PageThis.setData({
      [`${this.dataPath}.page_${pages}`]: [],
    });
    this.pages--;
  }
  removeItem(pages, index) {
    let pagePath = `${this.dataPath}.page_${pages}`;
    let pageData = this.PageThis["data"][this.dataPath]["page_" + pages];
    pageData.splice(index, 1);
    this.PageThis.setData(
      {
        [pagePath]: pageData,
      },
      () => {
        this.length--;
      }
    );
  }
  clean() {
    this.pages = 0;
    this.length = 0;
    this.loading = false;
    this.finished = false;
    this.loadPage = 1;
    this.PageThis.setData({
      [this.dataPath]: {},
    });
  }
}
export default DPagination;
